package leetcode.t1Array;

/**
 * @author K
 * @date 2024/1/23 13:37
 */
public class T4_FindMedianSortedArrays {



    /**
     * 4. 寻找两个正序数组的中位数
     *
     * @param nums1
     * @param nums2
     * @return
     */
    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int[] allNums = new int[nums1.length + nums2.length];
        int i = 0;
        int j = 0;
        int k = 0;
        while (i < nums1.length || j < nums2.length) {
            Integer iValue = null;
            if (i < nums1.length) {
                iValue = nums1[i];
            }

            Integer jValue = null;
            if (j < nums2.length) {
                jValue = nums2[j];
            }

            if (iValue == null && jValue != null) {
                allNums[k] = jValue;
                j++;
            } else if (iValue != null && jValue == null) {
                allNums[k] = iValue;
                i++;
            } else {
                if (iValue <= jValue) {
                    allNums[k] = iValue;
                    i++;
                } else {
                    allNums[k] = jValue;
                    j++;
                }
            }


            k++;
        }

        int allLength = allNums.length;
        if (allLength % 2 == 0) {
            return (double) (allNums[allLength / 2] + allNums[allLength / 2 - 1]) / 2;
        } else {
            return allNums[allLength / 2];
        }

    }

    public static void main(String[] args) {
        double result = findMedianSortedArrays(new int[]{1, 3}, new int[]{2});
        double result1 = findMedianSortedArrays(new int[]{1, 2}, new int[]{3, 4});
        System.out.println();
    }
}
